package com.wms_backend.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wms_backend.dao.UserDao;
import com.wms_backend.entity.Result;
import com.wms_backend.entity.User;
import com.wms_backend.security.UserDetailsImpl;
import com.wms_backend.service.BasicService;
import com.wms_backend.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.origin.SystemEnvironmentOrigin;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class BasicServiceImpl implements BasicService {

    @Autowired
    AuthenticationManager authenticationManager;

    @Autowired
    private UserDao userDao;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Result login(JSONObject param) {


        String userId = param.getString("userId");
        String password = param.getString("password");
//        if(userDao.existsUserByUserIdAndPassword(userId,password)){
//            Map<String, String > claims = new HashMap<>();
//            claims.put("userId",userId);
//            String jwt = JwtUtil.createToken(claims);
//            Map<String,String> m = new HashMap<String , String>();
//            m.put("token",jwt);
//            return Result.success(m);
//        }
//        else return Result.error("用户名或密码错误");


        Authentication authenticationToken = new UsernamePasswordAuthenticationToken(userId, password);
        Authentication authentication;
        try {
            authentication = authenticationManager.authenticate(authenticationToken);
        } catch (BadCredentialsException e) {
            return Result.error("用户名或密码错误");
        }


        SecurityContextHolder.getContext().setAuthentication(authentication);
        String jwt = JwtUtil.createToken(authentication);

        UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
        List<String> roles = userDetails.getAuthorities().stream()
                .map(item -> item.getAuthority())
                .collect(Collectors.toList());
        Map<String, Object> m = new HashMap<>();
        m.put("token", jwt);
        m.put("roles", roles);
        redisTemplate.opsForValue().set("login" + userId, JSON.toJSONString(userDetails));

        return Result.success(m);

    }


    @Override
    public Result register(JSONObject param) {
        String userId = param.getString("userId");
        if (userDao.existsByUserId(userId)) {
            return Result.error("用户id已存在");
        }
        String password = param.getString("password");
        User user = new User();
        user.setUserId(userId);
        user.setPassword(password);
        user.setName(param.getString("name"));
        user.setPhone(param.getString("phone"));
        user.setRoles("ROLE_USER");
        User u = userDao.save(user);
        if (u != null) {
            return Result.success();
        } else {
            return Result.error("注册错误");
        }
    }
}
